package com.fancon.android.gardenjokesx.widget;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.arnx.jsonic.JSON;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.fancon.android.cache.utils.StorageUtils;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.activity.DetailJokesActivity;
import com.fancon.android.gardenjokesx.activity.M05Activity;
import com.fancon.android.gardenjokesx.dialog.DialogReportJorke;
import com.fancon.android.gardenjokesx.entity.Comment;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.StringUtil;

public class DetailTopControlView extends RelativeLayout implements
		OnClickListener {
	private View shareBtn, addNew, reportBtn;
	private ImageButton likeBtn;
	private Context mContext;
	private JokeDetailHeader header;
	private Photo photo;
	private String saveName = "jorke_image";
	private String imagePath;

	public DetailTopControlView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		// TODO Auto-generated constructor stub
		LayoutInflater layoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		layoutInflater.inflate(R.layout.detail_top_layout, this);
		likeBtn = (ImageButton) findViewById(R.id.like_btn);
		shareBtn = findViewById(R.id.share_btn);
		addNew = findViewById(R.id.add_new);
		reportBtn = findViewById(R.id.flag_btn);
		likeBtn.setOnClickListener(this);
		shareBtn.setOnClickListener(this);
		addNew.setOnClickListener(this);
		reportBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == likeBtn) {
			if (header != null) {
				header.doLike();
			}
		} else if (v == addNew) {
			Intent intent = new Intent(mContext, M05Activity.class);
			intent.putExtra(Constant.PHOTO_ID, photo.getPhoto_id());
			intent.putExtra("viewed_user_id", photo.getUser().getUser_id());
			try {
				ArrayList<Comment> listComments = ((DetailJokesActivity) mContext)
						.getListComments();
				ArrayList<Comment> tmp = new ArrayList<Comment>();
				if (listComments.size() < 31) {
					tmp = listComments;
				} else {
					tmp = (ArrayList<Comment>) listComments.subList(0, 29);
				}
				intent.putExtra("listComment", JSON.encode(tmp));
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
			mContext.startActivity(intent);
		} else if (v == shareBtn) {
			Log.d("doshare", "vao onclick");
			doShare();
		} else if (v == reportBtn) {
			doReport();
		}
	}

	/**
	 * Report Jorke
	 */
	private void doReport() {
		if (photo != null) {
			DialogReportJorke reportJorke = new DialogReportJorke(mContext,
					photo.getPhoto_id(), photo.getUser().getUser_id(), false);
			reportJorke.show();
		}
	}

	/**
	 * Share Jorke
	 */
	private void doShare() {
		if (photo != null) {
			Log.d("doshare", "doshare");
			doSave(saveName, true);
		}

	}

	private Bitmap loadBitMap(String filrPath) {
		return BitmapFactory.decodeFile(filrPath);
	}

	private boolean externalStorageAvailable() {
		boolean mExternalStorageAvailable;
		boolean mExternalStorageWriteable;
		String state = Environment.getExternalStorageState();

		if (state.equals(Environment.MEDIA_MOUNTED)) {
			// We can read and write the media
			mExternalStorageAvailable = mExternalStorageWriteable = true;
		} else if (state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
			// We can only read the media
			mExternalStorageAvailable = true;
			mExternalStorageWriteable = false;
		} else {
			// Something else is wrong. It may be one of many other states, but
			// all we need
			// to know is we can neither read nor write
			mExternalStorageAvailable = mExternalStorageWriteable = false;
		}
		return mExternalStorageAvailable && mExternalStorageWriteable;
	}

	/**
	 * Save image and share if doShare is true
	 * 
	 * @param fname
	 * @param doShare
	 */
	private void doSave(String fname, boolean doShare) {
		String photoUrl = StringUtil
				.processImageLink(this.photo.getUrl_photo());
		String filename = String.valueOf(photoUrl.hashCode());
		// String base = Environment.getExternalStorageDirectory()
		// .getAbsolutePath().toString();
		File file = new File(StorageUtils.getIndividualCacheDirectory(mContext)
				.getAbsolutePath() + "/" + filename);
		if (file.exists()) {
			imagePath = StorageUtils.getIndividualCacheDirectory(mContext)
					.getAbsolutePath() + "/" + filename;
		} else {
			return;
		}
		CharSequence text = getResources().getString(R.string.image_saved_as)
				+ " ";
		try {
			String ReservedChars = "|\\?*<\":>+[]/'";
			for (char c : ReservedChars.toCharArray()) {
				fname = fname.replace(c, '_');
			}
			String value = fname;
			Bitmap b = loadBitMap(imagePath);
			if (b == null) {
				// text = getResources().getString(R.string.image_save_fail_1);
				Toast.makeText(mContext, "not ok", Toast.LENGTH_LONG).show();
				return;
			}
			File folder = mContext.getFilesDir();
			if (externalStorageAvailable()) {
				try {
					folder = Environment
							.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
					if (!folder.exists() || !folder.canWrite()) {
						folder = Environment
								.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
					}
					if (!folder.exists() || !folder.canWrite()) {
						folder = Environment.getExternalStorageDirectory();
					}
				} catch (Exception e) {
					folder = Environment.getExternalStorageDirectory();
				} catch (Error e) {
					folder = Environment.getExternalStorageDirectory();
				}
				if (!folder.exists() || !folder.canWrite()) {
					folder = mContext.getFilesDir();
				}
			}

			String ext = ".jpg";
			String fullname = folder.getAbsolutePath() + File.separator + value
					+ ext;
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("filename", fullname);
			FileOutputStream fos;
			if (folder == mContext.getFilesDir())
				fos = mContext.openFileOutput(value + ext,
						Context.MODE_WORLD_WRITEABLE);
			else {
				File f2 = new File(fullname);// openFileOutput(fname,
												// Context.MODE_PRIVATE);//new
												// FileOutputStream(fullname);
				fos = new FileOutputStream(f2);
			}
			if (ext.equals(".png"))
				b.compress(CompressFormat.PNG, 95, fos);
			else
				b.compress(CompressFormat.JPEG, 95, fos);
			fos.close();
			String[] str = new String[1];
			str[0] = fullname;
			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
				MediaScannerConnection.scanFile(mContext, str, null, null);
			}
			text = text + value + ext + " "
					+ getResources().getString(R.string.saved_end);
			saveName = value;
			// setDetailTitle ();
			if (doShare) {
				Intent share = new Intent(Intent.ACTION_SEND);
				if (photo.getUrl_photo() != Constant.NO_COMIC) {
					share.setType("image/*");
				} else {
					share.setType("text/plain");
				}
				share.putExtra(Intent.EXTRA_TITLE, mContext.getResources()
						.getString(R.string.share_jorke));
				share.putExtra(Intent.EXTRA_TEXT, photo.getCaption());
				share.putExtra(Intent.EXTRA_STREAM,
						Uri.parse("file://" + fullname.replace(" ", "%20")));

				mContext.startActivity(Intent.createChooser(share, mContext
						.getResources().getString(R.string.share_jorke)));
			}
		} catch (Exception e) {
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("text", e.toString());
			e.printStackTrace();
			// text = getResources().getString(R.string.image_save_fail_2)
			// + e.toString();
		} catch (Error e) {
			Map<String, String> hm = new HashMap<String, String>();
			hm.put("text", e.toString());
			e.printStackTrace();
			// text = getResources().getString(R.string.image_save_fail_2)
			// + e.toString();
		}
		// Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

	public JokeDetailHeader getHeader() {
		return header;
	}

	public void setHeader(JokeDetailHeader header) {
		this.header = header;
	}

	public void like() {
		likeBtn.setImageResource(R.drawable.ic_favorite_red);
	}

	public void unLike() {
		likeBtn.setImageResource(R.drawable.ic_favorite);
	}

	public Photo getPhoto() {
		return photo;
	}

	public void setPhoto(Photo photo) {
		this.photo = photo;
	}

}
